<template>
  <div class='ele-body ele-body-card'>
    <!-- 顶部卡片 -->
    <a-card
      :bordered='true'
      :body-style="{padding: '20px'}">
      <div class='ele-cell workplace-user-card'>
        <div class='ele-cell-content ele-cell'>
          <a-progress :width='70' type='circle' :percent='100' :format="() => '柜子'" />
          <div class='ele-cell-content'>
            <h4 class='ele-elip'>设备号：{{ data.recordId }}</h4>
            <div class='ele-elip ele-text-secondary'>
              <clock-circle-outlined />
              <em>{{ data.deviceTime }}</em>
            </div>
          </div>
        </div>
      </div>
    </a-card>

    <a-card
      :bordered='true'
      :body-style="{padding: '20px'}">
      <a-form
        ref='timeformRef'
        :model='timeformModel'
        :rules="dateTimeRules"
        :label-col='{ md: { span: 7 }, sm: { span: 24 } }'
        :wrapper-col='{ md: { span: 17 }, sm: { span: 24 } }'
        @submit='setTimeActionToCmdQueue'
      >
        <a-row :gutter='8'>
          <a-col :md='10' :sm='24' :xs='24'>
            <a-form-item label='设备时间:' name='ddate'>
              <a-date-picker
                v-model:value="timeformModel.ddate"
                type='date'
                show-time
                placeholder="选择时间"
                format="YYYY-MM-DD HH:mm:ss"
              />
              <br/>
              当前时间:{{currentTime}}
            </a-form-item>

          </a-col>
          <a-col :md='2' :sm='24' :xs='24'>
            <a-button v-permission="['PROPERTY_DEVICELIST_MGR_ROLLERSHADES_CONFIG_SETTIME_BUTTON']" type='primary' html-type='submit' :loading='timeformRefLoading'>
              提交
            </a-button>
          </a-col>
          <a-col :md='1' :sm='24' :xs='24'>
          </a-col>
          <a-col :md='11' :sm='24' :xs='24'>
            <a-button v-permission="['PROPERTY_DEVICELIST_MGR_ROLLERSHADES_CONFIG_READTIME_BUTTON']" type='primary' html-type='button' @click="queryTimeActionToCmdQueue" :loading='queryTimeLoading'>
              读取设备时间
            </a-button>
          </a-col>
        </a-row>
      </a-form>
    </a-card>

    <a-card
      :bordered='true'
      :body-style="{padding: '20px'}">
      <a-form
        ref='gatewaytimeformRef'
        :model='gatewaytimeformModel'
        :rules="gatewaytimeRules"
        :label-col='{ md: { span: 7 }, sm: { span: 24 } }'
        :wrapper-col='{ md: { span: 17 }, sm: { span: 24 } }'
        @submit='setHeartIntervalActionToCmdQueue'
      >
        <a-row :gutter='8'>
          <a-col :md='10' :sm='24' :xs='24'>
            <a-form-item label='网关的握手时间间隔(秒):' name='heartInterval'>
              <a-input v-model:value='gatewaytimeformModel.heartInterval' placeholder='请输入间隔时间，单位s' allow-clear />
            </a-form-item>
          </a-col>
          <a-col :md='2' :sm='24' :xs='24'>
            <a-button v-permission="['PROPERTY_DEVICELIST_MGR_ROLLERSHADES_CONFIG_SETHEARTBEAT_BUTTON']" type='primary' html-type='submit' :loading='gatewaytimeformRefLoading'>
              提交
            </a-button>
          </a-col>
          <a-col :md='1' :sm='24' :xs='24'/>
          <a-col :md='11' :sm='24' :xs='24'>
            <a-button v-permission="['PROPERTY_DEVICELIST_MGR_ROLLERSHADES_CONFIG_READ_HEARTBEAT_BUTTON']" type='primary' html-type='button' @click='queryHeartIntervalActionToCmdQueue' :loading='queryTheartIntervalLoading'>
              读取时间间隔
            </a-button>
          </a-col>
        </a-row>
      </a-form>
    </a-card>

    <a-card
      :bordered='true'
      :body-style="{padding: '20px'}">
      <a-form
        ref='ipPortformRef'
        :model='ipPortformModel'
        :rules="ipPortRules"
        :label-col='{ md: { span: 7 }, sm: { span: 24 } }'
        :wrapper-col='{ md: { span: 17 }, sm: { span: 24 } }'
        @submit='setIpPortActionToCmdQueue'
      >
        <a-row :gutter='8'>
          <a-col :md='10' :sm='24' :xs='24'>
            <a-form-item label='数据采集IP:' name='ip'>
              <a-input v-model:value='ipPortformModel.ip' placeholder='请输入ip，例如10.10.10.10' allow-clear />
            </a-form-item>
          </a-col>
          <a-col :md='12' :sm='24' :xs='24'>
          </a-col>
        </a-row>
        <a-row :gutter='8'>
          <a-col :md='10' :sm='24' :xs='24'>
            <a-form-item label='数据采集端口:' name='port'>
              <a-input v-model:value='ipPortformModel.port' placeholder='请输入ip，例如8000' allow-clear />
            </a-form-item>
          </a-col>
          <a-col :md='12' :sm='24' :xs='24'>
            <a-button v-permission="['PROPERTY_DEVICELIST_MGR_ROLLERSHADES_CONFIG_SET_IPPORT_BUTTON']" type='primary' html-type='submit' :loading='ipPortformRefLoading'>
              提交
            </a-button>
          </a-col>
        </a-row>
      </a-form>
    </a-card>


    <a-card
      :bordered='true'
      :body-style="{padding: '20px'}">
      <a-form
        ref='dominPortformRef'
        :model='dominPortformModel'
        :rules="dominPortRules"
        :label-col='{ md: { span: 7 }, sm: { span: 24 } }'
        :wrapper-col='{ md: { span: 17 }, sm: { span: 24 } }'
        @submit='setDominPortActionToCmdQueue'
      >
        <a-row :gutter='8'>
          <a-col :md='10' :sm='24' :xs='24'>
            <a-form-item label='数据采集域名:' name='ip'>
              <a-input v-model:value='dominPortformModel.domin' placeholder='请输入域名' allow-clear />
            </a-form-item>
          </a-col>
          <a-col :md='12' :sm='24' :xs='24'>
          </a-col>
        </a-row>
        <a-row :gutter='8'>
          <a-col :md='10' :sm='24' :xs='24'>
            <a-form-item label='数据采集端口:' name='port'>
              <a-input v-model:value='dominPortformModel.port' placeholder='请输入端口，例如8000' allow-clear />
            </a-form-item>
          </a-col>
          <a-col :md='12' :sm='24' :xs='24'>
            <a-button v-permission="['PROPERTY_DEVICELIST_MGR_ROLLERSHADES_CONFIG_SET_DOMIN_BUTTON']" type='primary' html-type='submit' :loading='dominPortformRefLoading'>
              提交
            </a-button>
          </a-col>
        </a-row>
      </a-form>
    </a-card>
  </div>
</template>

<script>
import ClockCircleOutlined from '@ant-design/icons-vue/lib/icons/ClockCircleOutlined';
import {DeviceCommandDownQueueApi} from '@/api/property/DeviceCommandDownQueueApi';
import { message } from 'ant-design-vue';
import { DeviceRecordApi } from '@/api/property/DeviceRecordApi';
import {DeviceRollershadesConfigApi} from "@/api/property/rollershades/DeviceRollershadesConfigApi";

export default {
  name: 'DeviceRollershadesConfigOther',
  components: {
    ClockCircleOutlined
  },
  props: {
    data: Object
  },
  async created() {
    await this.init();
  },
  data() {
    return {
      currentTime : '',
      loading : false,
      timeformModel : {},
      dateTimeRules: {
        // ddate : [
        //   { type: 'string', required: true, message: '请选择时间' }
        // ]
      },
      timeformRefLoading : false,
      timeformRefTimer : undefined,

      gatewaytimeformModel : {},
      gatewaytimeRules : {},
      gatewaytimeformRefLoading : false,
      gatewaytimeformRefTimer : undefined,

      ipPortformModel: {},
      ipPortRules : {},
      ipPortformRefLoading: false,
      ipPortformRefTimer : undefined,

      dominPortformModel: {},
      dominPortRules : {},
      dominPortformRefLoading: false,
      dominPortformRefTimer : undefined,


      queryTimeLoading : false,
      queryTimeTimer : undefined,

      queryTheartIntervalLoading : false,
      queryTheartIntervalTimer : undefined
    };
  },
  methods: {
    async init() {
      let _conf = await DeviceRollershadesConfigApi.detail({ 'recordId': this.data.recordId });
      if (_conf) {
        this.gatewaytimeformModel.heartInterval = _conf.heartIntervalTime ? _conf.heartIntervalTime : undefined;
      }

      let _deviceRecordInfo = await DeviceRecordApi.detail({ 'recordId': this.data.recordId });
      if (_deviceRecordInfo) {
        console.log(_deviceRecordInfo);
        this.currentTime = _deviceRecordInfo.deviceTime ? _deviceRecordInfo.deviceTime : '';
      }
    },
    checkProcess(sceneDictate, clearCallback, callback) {
      let params = {
        recordId: this.data.recordId,
        sceneDictate: sceneDictate
      };
      let result = DeviceCommandDownQueueApi.workingDetail(params);
      result
        .then(result => {
          if (!result || !result.dcdqId) { //处理完成了
            clearCallback && clearCallback(); //去掉菊花+清除循环调用
            callback && callback(); //用户自定义
          }
        })
        .catch(() => {
          clearCallback && clearCallback(); //去掉菊花+清除循环调用
        });
    },

    //设置时间----begin
    clearTimeformRef(){
      this.timeformRefLoading = false;
      clearInterval(this.timeformRefTimer); //清除循环调用
    },
    checkTimeformRef(){
      let that = this;
      this.checkProcess(0, this.clearTimeformRef, function(){
        that.timeformModel.ddate = undefined;
        that.init();
      });
    },
    setTimeActionToCmdQueue()
    {
      let workerDetailparams = {
        recordId: this.data.recordId,
        sceneDictate: 0
      };
      let that = this;
      let existWorkerResult = DeviceCommandDownQueueApi.workingDetail2(workerDetailparams);
      existWorkerResult
        .then(workResult => {
          console.log(workResult);
          if (!workResult || !workResult.dcdqId) { //处理完成了
            that.pushDateTime();
          } else {
            message.error('上一个配置还在推送中，请稍后重试');
            return;
          }
        })
        .catch((e) => {
          message.error(e);
        });
    },
    pushDateTime() {
      if (!this.timeformModel.ddate) {
        message.error('请先填写时间');
        return;
      }
      this.loading = true;
      let updateDataRecord = {
        recordId: this.data.recordId,
        templateCode: 'rollershades',
        updateData: JSON.stringify({ old: '', update: {date : this.timeformModel.ddate.format("YYYY-MM-DD HH:mm:ss")}}),
        dictate : 0,
        sceneDictate : 0
      };

      let result = DeviceCommandDownQueueApi.add(updateDataRecord);
      result
        .then(result => {
          // 移除加载框
          this.loading = false;
          // 提示添加成功
          message.success(result.message);
          this.timeformRefLoading = true; //转圈
          this.timeformRefTimer = setInterval(this.checkTimeformRef, 5000);
        })
        .catch(() => {
          this.loading = false;
        });
    },
    //设置时间----end


    //读取设备时间--begin
    clearQueryTime(){
      this.queryTimeLoading = false;
      clearInterval(this.queryTimeTimer);
    },
    checkQueryTime(){
      let that = this;
      this.checkProcess(32, this.clearQueryTime, function(){
        that.init();
      });
    },
    queryTimeActionToCmdQueue()
    {
      let workerDetailparams = {
        recordId: this.data.recordId,
        sceneDictate: 32
      };
      let that = this;
      let existWorkerResult = DeviceCommandDownQueueApi.workingDetail2(workerDetailparams);
      existWorkerResult
        .then(workResult => {
          console.log(workResult);
          if (!workResult || !workResult.dcdqId) { //处理完成了
            that.queryTime();
          } else {
            message.error('上一个配置还在推送中，请稍后重试');
            return;
          }
        })
        .catch((e) => {
          message.error(e);
        });
    },

    queryTime() { //获取时间
      this.loading = true;
      let updateDataRecord = {
        recordId: this.data.recordId,
        templateCode: 'rollershades',
        updateData: JSON.stringify({ old: '', update: ''}),
        dictate : 32,
        sceneDictate : 32
      };
      let result = DeviceCommandDownQueueApi.add(updateDataRecord);
      result
        .then(result => {
          this.loading = false;
          message.success(result.message);

          this.queryTimeLoading = true; //转圈
          this.queryTimeTimer = setInterval(this.checkQueryTime, 5000);
        })
        .catch(() => {
          this.loading = false;
        });
    },
    //读取设备时间--end


    //网关的握手时间间隔设置--begin
    clearGatewaytimeformRef(){
      this.gatewaytimeformRefLoading = false;
      clearInterval(this.gatewaytimeformRefTimer);
    },
    checkHeartInterval(){
      let that = this;
      this.checkProcess(6, this.clearGatewaytimeformRef, function(){
        that.gatewaytimeformModel.heartInterval = undefined;
        that.init();
      });
    },
    setHeartIntervalActionToCmdQueue()
    {
      let workerDetailparams = {
        recordId: this.data.recordId,
        sceneDictate: 6
      };
      let that = this;
      let existWorkerResult = DeviceCommandDownQueueApi.workingDetail2(workerDetailparams);
      existWorkerResult
        .then(workResult => {
          console.log(workResult);
          if (!workResult || !workResult.dcdqId) { //处理完成了
            that.pushHeartInterval();
          } else {
            message.error('上一个配置还在推送中，请稍后重试');
            return;
          }
        })
        .catch((e) => {
          message.error(e);
        });
    },
    pushHeartInterval() {
      if (!this.gatewaytimeformModel.heartInterval) {
        message.error('请先填写间隔时间');
        return;
      }
      this.loading = true;
      let updateDataRecord = {
        updateData: JSON.stringify({ old: '', update: {heartInterval : this.gatewaytimeformModel.heartInterval}}),
        recordId: this.data.recordId,
        templateCode: 'rollershades',
        dictate : 6,
        sceneDictate : 6
      };
      let result = DeviceCommandDownQueueApi.add(updateDataRecord);
      result
        .then(result => {
          this.loading = false;
          message.success(result.message);

          this.gatewaytimeformRefLoading = true; //转圈
          this.gatewaytimeformRefTimer = setInterval(this.checkHeartInterval, 5000);
        })
        .catch(() => {
          this.loading = false;
        });
    },
    //网关的握手时间间隔设置--end


    //读取网关的握手时间间隔设置--begin
    clearQueryTheartInterval(){
      this.queryTheartIntervalLoading = false;
      clearInterval(this.queryTheartIntervalTimer);
    },
    checkQeuryHealthInterval(){
      let that = this;
      this.checkProcess(37, this.clearQueryTheartInterval, function(){
        that.gatewaytimeformModel.heartInterval = undefined;
        that.init();
      });
    },
    queryHeartIntervalActionToCmdQueue()
    {
      let workerDetailparams = {
        recordId: this.data.recordId,
        sceneDictate: 37
      };
      let that = this;
      let existWorkerResult = DeviceCommandDownQueueApi.workingDetail2(workerDetailparams);
      existWorkerResult
        .then(workResult => {
          console.log(workResult);
          if (!workResult || !workResult.dcdqId) { //处理完成了
            that.queryHealthInterval();
          } else {
            message.error('上一个配置还在推送中，请稍后重试');
            return;
          }
        })
        .catch((e) => {
          message.error(e);
        });
    },
    queryHealthInterval() { //获取时间
      this.loading = true;
      let updateDataRecord = {
        updateData: JSON.stringify({ old: '', update: ''}),
        recordId: this.data.recordId,
        templateCode: 'rollershades',
        dictate : 37,
        sceneDictate : 37
      };
      let result = DeviceCommandDownQueueApi.add(updateDataRecord);
      result
        .then(result => {
          this.loading = false;
          message.success(result.message);

          this.queryTheartIntervalLoading = true; //转圈
          this.queryTheartIntervalTimer = setInterval(this.checkQeuryHealthInterval, 5000);
        })
        .catch(() => {
          this.loading = false;
        });
    },

    //读取网关的握手时间间隔设置--end

    //设置ip begin
    clearIpPortformRef(){
      this.ipPortformRefLoading = false;
      clearInterval(this.ipPortformRefTimer);
    },
    checkIpPort(){
      let that = this;
      this.checkProcess(7, this.clearIpPortformRef, function(){
        that.ipPortformModel.ip = undefined;
        that.ipPortformModel.port = undefined;
      });
    },
    setIpPortActionToCmdQueue()
    {
      let workerDetailparams = {
        recordId: this.data.recordId,
        sceneDictate: 7
      };
      let that = this;
      let existWorkerResult = DeviceCommandDownQueueApi.workingDetail2(workerDetailparams);
      existWorkerResult
        .then(workResult => {
          console.log(workResult);
          if (!workResult || !workResult.dcdqId) { //处理完成了
            that.pushIpPort();
          } else {
            message.error('上一个配置还在推送中，请稍后重试');
            return;
          }
        })
        .catch((e) => {
          message.error(e);
        });
    },
    pushIpPort() {
      if (!this.ipPortformModel.ip || !this.ipPortformModel.port) {
        message.error('请先填写ip和端口');
        return;
      }
      this.loading = true;
      let updateDataRecord = {
        updateData: JSON.stringify({
          old: '',
          update: {
            ip : this.ipPortformModel.ip,
            port : this.ipPortformModel.port
          }
        }),
        recordId: this.data.recordId,
        templateCode: 'rollershades',
        dictate : 7,
        sceneDictate : 7
      };
      let result = DeviceCommandDownQueueApi.add(updateDataRecord);
      result
        .then(result => {
          this.loading = false;
          message.success(result.message);

          this.ipPortformRefLoading = true; //转圈
          this.ipPortformRefTimer = setInterval(this.checkIpPort, 5000);
        })
        .catch(() => {
          this.loading = false;
        });
    },
    //设置ip end


    //设置域名 begin
    clearDominPortformRef(){
      this.dominPortformRefLoading = false;
      clearInterval(this.dominPortformRefTimer);
    },
    checkDominPort(){
      let that = this;
      this.checkProcess(10, this.clearDominPortformRef, function(){
        that.dominPortformModel.domin = undefined;
        that.dominPortformModel.port = undefined;
      });
    },
    setDominPortActionToCmdQueue()
    {
      let workerDetailparams = {
        recordId: this.data.recordId,
        sceneDictate: 10
      };
      let that = this;
      let existWorkerResult = DeviceCommandDownQueueApi.workingDetail2(workerDetailparams);
      existWorkerResult
        .then(workResult => {
          console.log(workResult);
          if (!workResult || !workResult.dcdqId) { //处理完成了
            that.pushDominPort();
          } else {
            message.error('上一个配置还在推送中，请稍后重试');
            return;
          }
        })
        .catch((e) => {
          message.error(e);
        });
    },
    pushDominPort() {
      if (!this.dominPortformModel.domin || !this.dominPortformModel.port) {
        message.error('请先填写域名和端口');
        return;
      }
      this.loading = true;
      let updateDataRecord = {
        updateData: JSON.stringify({
          old: '',
          update: {
            domin : this.dominPortformModel.domin,
            port : this.dominPortformModel.port
          }
        }),
        recordId: this.data.recordId,
        templateCode: 'rollershades',
        dictate : 10,
        sceneDictate : 10
      };
      let result = DeviceCommandDownQueueApi.add(updateDataRecord);
      result
        .then(result => {
          this.loading = false;
          message.success(result.message);

          this.dominPortformRefLoading = true; //转圈
          this.dominPortformRefTimer = setInterval(this.checkDominPort, 5000);
        })
        .catch(() => {
          this.loading = false;
        });
    },
    //设置域名 end

  }
};
</script>
<style scoped>
/** 用户卡片 */
.workplace-user-card .ele-cell-content {
  overflow: hidden;
}

.workplace-user-card h4 {
  margin-bottom: 6px;
}
</style>
